//EXPLOSION

AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include( 'shared.lua' )

ENT.iOwner = nil
ENT.HitSound = Sound("ambient/fire/mtov_flame2.wav")

function takedamageball(owner,target)
local dano = math.random( 10, 40 )
if target:Health() - dano > 0 then
target:SetHealth( target:Health() - dano )
elseif target:Health() - dano <= 0 then
target.whoKilled = owner
target:Kill()
end
end

function explodeball(ent,iOwner)
	local vPoint = ent:GetPos() + Vector(0,0,1)
	local effectdata = EffectData()
	effectdata:SetStart( vPoint )
	effectdata:SetOrigin( vPoint )
	effectdata:SetScale( 0.5 )
	util.Effect( "Explosion", effectdata, true, true )
	local nearEnts = ents.FindInSphere( ent:GetPos(), 190 )
	for k,v in pairs(nearEnts) do
		if (v:IsPlayer() and v != iOwner and v:Team() !=  iOwner:Team()) then 
			takedamageball(iOwner,v)
		end
	end
end

function ENT:SpawnFunction( ply, tr )

	if ( !tr.Hit ) then return end
	
	local SpawnPos = tr.HitPos + tr.HitNormal * 16
	
	local ent = ents.Create( "explosion_ball" )
		ent:SetPos( SpawnPos )
	ent:Spawn()
	ent:Activate()
	
	return ent
	
end

function ENT:Initialize()

	self.Entity:SetModel( "models/Combine_Helicopter/helicopter_bomb01.mdl" )
	
	self.Entity:PhysicsInitSphere( 13, "metal_bouncy" )
	
	local phys = self.Entity:GetPhysicsObject()
	if (phys:IsValid()) then
		phys:Wake()
	end
	
	self.Entity:SetCollisionBounds( Vector( -13, -13, -13 ), Vector( 13, 13, 13 ) )
	
	util.SpriteTrail( self.Entity, 0, Color(50, 50, 50), true, 22, 0, 0.7, 1/(18+1)*0.5, "trails/plasma.vmt" )
	
	timer.Create("T"..tostring(math.Rand(0,10000))..tostring(CurTime()/10),3,1, function()
		if ValidEntity(self.Entity) then
			explodeball(self.Entity,self.iOwner)
			self.Entity:Remove()
		end	
	end)
end

function ENT:PhysicsCollide( data, physobj )
if ValidEntity(self.Entity) then
	explodeball(self.Entity,self.iOwner)
end	
end

function ENT:OnTakeDamage( dmginfo )
	self.Entity:TakePhysicsDamage( dmginfo )
end


function ENT:Touch( entidadeTocada )

	if !ValidEntity(entidadeTocada) then return end
	if !entidadeTocada:IsPlayer() then return end
	if entidadeTocada == self.Entity.iOwner or entidadeTocada:Team() == self.Entity.iOwner:Team() then return end
	
	entidadeTocada:EmitSound(self.Entity.HitSound)
	
	local dano = math.random( 2, 7 )
	if entidadeTocada:Health() - dano > 0 then
	
		entidadeTocada:SetHealth( entidadeTocada:Health() - dano )
		entidadeTocada:PrintMessage( HUD_PRINTCENTER, "Exploded!") 
		entidadeTocada:Ignite(0.6,0)
		
	elseif entidadeTocada:Health() - dano <= 0 then
	
		entidadeTocada.whoKilled = self.Entity.iOwner
		entidadeTocada:Kill()
	
	end
	
	//efeito...

      umsg.Start("FireLockMsg", entidadeTocada)
      umsg.Bool( true )
      umsg.End()
	
	self.Entity:Remove()

end



